/** @jsxImportSource react */
'use client'

import React, { useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useEffect } from 'react'
import { API_CONFIG } from '../config';

interface CartItem {
  id: number
  name: string
  strength: string
  price: number
  quantity: number
  image: string
}

export default function CartPage() {
  const [cartItems, setCartItems] = useState<CartItem[]>(() => {
    const existingCart = localStorage.getItem('cart');
    return existingCart ? JSON.parse(existingCart) : [];
  });

  useEffect(() => {
    const existingCart = localStorage.getItem('cart');
    if (existingCart) {
      setCartItems(JSON.parse(existingCart));
    }
  }, []);

  const updateQuantity = (id: number, newQuantity: number) => {
    setCartItems((items: CartItem[]) => {
      const newItems = items.map((item: CartItem) =>
        item.id === id ? { ...item, quantity: Math.max(0, newQuantity) } : item
      );
      localStorage.setItem('cart', JSON.stringify(newItems));
      return newItems;
    });
  };

  const removeItem = (id: number) => {
    setCartItems((items: CartItem[]) => {
      const newItems = items.filter((item: CartItem) => item.id !== id);
      localStorage.setItem('cart', JSON.stringify(newItems));
      return newItems;
    });
  };

  const subtotal = cartItems.reduce((sum: number, item: CartItem) => sum + item.price * item.quantity, 0)
  const shipping = 5.99
  const total = subtotal + shipping

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container py-16">
        <h1 className="text-4xl font-bold mb-8">Shopping Cart</h1>
        <div className="hidden lg:block">
          {/* 购物车图标代码 */}
        </div>

        {cartItems.length > 0 ? (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Cart Items */}
            <div className="lg:col-span-2">
              <div className="bg-white rounded-lg shadow-sm">
                {cartItems.map((item) => (
                  <div key={item.id} className="p-6 border-b last:border-b-0">
                    <div className="flex flex-col md:flex-row">
                      {/* 商品图片 */}
                      <div className="relative w-24 h-24 flex-shrink-0 mb-4 md:mb-0">
                        <Image
                          src={`${API_CONFIG.BASE_URL}${item.image}`}
                          alt={item.name}
                          fill
                          className="object-cover rounded"
                        />
                      </div>
                      
                      {/* 商品信息和操作按钮 */}
                      <div className="flex-1 md:ml-6">
                        <div className="flex flex-col md:flex-row justify-between">
                          {/* 商品信息 */}
                          <div className="mb-4 md:mb-0">
                            <h3 className="text-lg font-medium">{item.name}</h3>
                            <p className="text-gray-600">Strength: {item.strength}</p>
                            <p className="text-primary font-medium">${Number(item.price).toFixed(2)}</p>
                          </div>
                          
                          {/* 操作按钮 */}
                          <div className="flex items-center space-x-4">
                            <div className="flex items-center border rounded">
                              <button
                                onClick={() => updateQuantity(item.id, item.quantity - 1)}
                                className="inline-block bg-[#ff4d8c] text-white px-2 py-1 rounded hover:bg-[#ff3377] transition-colors"
                              >
                                -
                              </button>
                              <span className="px-3 py-1 border-x">{item.quantity}</span>
                              <button
                                onClick={() => updateQuantity(item.id, item.quantity + 1)}
                                className="inline-block bg-[#ff4d8c] text-white px-2 py-1 rounded hover:bg-[#ff3377] transition-colors"
                              >
                                +
                              </button>
                            </div>
                            <button
                              onClick={() => removeItem(item.id)}
                              className="inline-block bg-[#ff4d8c] text-white px-6 py-2 rounded hover:bg-[#ff3377] transition-colors"
                            >
                              Remove
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Order Summary */}
            <div className="lg:col-span-1">
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-semibold mb-4">Order Summary</h2>
                <div className="space-y-4">
                  {cartItems.map((item) => (
                    <div key={item.id} className="flex justify-between">
                      <span>{item.name}</span>
                      <span>${Number(item.price * item.quantity).toFixed(2)}</span>
                    </div>
                  ))}
                  <div className="border-t pt-4">
                    <div className="flex justify-between font-semibold">
                      <span>Total</span>
                      <span>${Number(subtotal).toFixed(2)}</span>
                    </div>
                  </div>
                </div>
                <button 
                  className="inline-block bg-[#ff4d8c] text-white px-6 py-2 rounded hover:bg-[#ff3377] transition-colors w-full mt-6"
                  onClick={() => {
                    const cartData = localStorage.getItem('cart');
                    if (cartData) {
                      const url = new URL('/order', window.location.origin);
                      url.searchParams.set('cartData', encodeURIComponent(cartData));
                      window.location.href = url.toString();
                    } else {
                      window.location.href = '/order';
                    }
                  }}
                >
                  Proceed to Checkout
                </button>
              </div>
            </div>
          </div>
        ) : (
          <div className="text-center py-16">
            <h2 className="text-2xl font-medium mb-4">Your cart is empty</h2>
            <p className="text-gray-600 mb-8">
              Looks like you haven't added any items to your cart yet.
            </p>
            <Link href="/shop" className="btn-primary">
              Start Shopping
            </Link>
          </div>
        )}
      </div>
    </div>
  )
}